import startsWith from 'lodash/startsWith';
import filter from 'lodash/filter';
import {removeArrayItem} from './removeArrayItem';

const manager={

};
let id=0;
export const genId=()=>{
    return 'genNs_'+id++;
};
export const add=(data,ns,...args)=>{
    const id=genId();
    const item={
        id,
        path:ns,
        value:args
    };
    data.push(item);
    data._map[id]=item;
    return item;
};
const genNsFilter=(ns,fn)=>(item)=>{
    const {path,value=[]}=item;
    let flag=false;
    if(typeof ns==='string'){
        flag=startsWith(path,ns);
    }else if(ns instanceof RegExp){
        flag=ns.test(path);
    }
    if(!flag||!fn){
        return flag;
    }
    return fn===value[0];
};
export const get=(data,ns,fn)=>{
    if(!ns){
        return [...data];
    }
    const nsFilter=genNsFilter(ns,fn);
    return filter(data,nsFilter);
};
export const getById=(data,id)=>{
    return data._map[id];
};
export const removeById=(data,id)=>{
    const item=getById(data,id);
    if(!item){
        return;
    }
    const index=data.indexOf(item);
    data.splice(index,1);
    delete data._map[id];
};
export const genNs=()=>{
    let data=[
        // {path:'',value:null}
    ];
    data._map={};
    return {
        getData(){
            return data;
        },
        add:(...args)=>add(data,...args),
        get:(ns,fn)=>get(data,ns,fn),
        getById:(id)=>getById(data,id),
        removeById:id=>removeById(data,id),
        remove(ns,fn){
            const nsFilter=genNsFilter(ns,fn);
            removeArrayItem(data,nsFilter,(item)=>{
                removeById(data,item.id);
            });
        },
        forEachValue:(ns,fn)=>{
            const datas=get(data,ns,fn);
            datas.forEach((data)=>{
                fn(...data.value,data);
            });
        }
    }
};

export default genNs;